﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using MIL.Html;
using System.Globalization;

namespace Site_Extractor
{
	public class ForumYnet//:IForumExtractor
	{
		// TODO: do it again, but nicely ...

		/*private static string _mainLink = "http://www.ynet.co.il/home/0,7340,L-2330,00.html";
		private static string _forumLink = "http://www.ynet.co.il/home/0,7340,L-{0}-{1},00.html";

		#region IForumExtractor Members

		private static char sep1 = '-', sep2=',';

		public YnetForumId[] GetAllForumIds(bool notNeeded)
		{
			if (notNeeded) return new YnetForumId[0];
			string url = _mainLink;

			YnetForumId id;
			List<YnetForumId> forumIds = new List<YnetForumId>();
			long major, minor;

			List<string> visited = new List<string>();
			var links = Crawler.Crawl(url, ref visited, 0);
			foreach (string link in links)
			{
				if (!link.Contains("ynet.co.il/home/0,7340,L") || link.LastIndexOf(sep1) == link.IndexOf(sep1)) continue;
				GetIdFromLink(link, out major, out minor);
				id = new YnetForumId(major, minor);
				if (major == 0 || minor == 0 || forumIds.Contains(id)) continue;
				forumIds.Add(id);
			}

			var sorted = from l in forumIds
						 orderby l.Major, l.Minor
						 select l;

			return sorted.ToArray();
		}

		public long[] GetAllForumIds()
		{
			return new long[0];
		
		}

		private void GetIdFromLink(string link, out long major, out long minor)
		{
			int start, end;
			start = link.IndexOf(sep1);
			end = link.LastIndexOf(sep1);
			if (!long.TryParse(link.Substring(start + 1, end - start - 1), out major)) { major = minor = 0; return; }
			start = end;
			end = link.LastIndexOf(sep2);
			if (!long.TryParse(link.Substring(start + 1, end - start - 1), out minor)) { major = minor = 0; return; }
		}

		public Forum ExtractForum(YnetForumId id)
		{
			Forum f = new Forum();
			string url = string.Format(_forumLink, id.Major, id.Minor);
			f.Name = string.Format("{0} / {1}", id.Major, id.Minor);
			f.Url = url;

			var page = HtmlDownloader.DownloadPage(new Uri(url),Encoding.UTF8);
			var nodes = HtmlDownloader.GetNodes(page);

			string allVars = GetAllVars(page);
			List<string> messageIds = new List<string>();
			GetAllMessageIds(page, ref messageIds);
			foreach (string msgId in messageIds)
			{
				GetMessage(msgId, allVars, ref f.Messages);
			}

			return f;
		}

		private void GetMessage(string msgId, string allVars, ref List<ForumMessage> list)
		{
			
			 * Adrs = '/NRFrame/Ext/App/TDG/TDGDisplayMessage/0,9734,ToReplace,00.html'
			Adrs = Adrs.replace ('ToReplace',ALLVAR);

			 * 
			 * 
			msgId = msgId.Trim();
			string link = "http://www.ynet.co.il/NRFrame/Ext/App/TDG/TDGDisplayMessage/0,9734,ToReplace,00.html";
			string allVar = string.Format(allVars, msgId);
			link = link.Replace("ToReplace", allVar);
			var page = HtmlDownloader.DownloadPage(new Uri(link));
			var nodes = HtmlDownloader.GetNodes(page);

			// need to extract all the text + date ...
			
			var topicNode = SiteExtractor.GetNodeByRule(nodes, new Rule("font", "class", "text18")) as HtmlElement;
			//var textNode = SiteExtractor.GetNodeByRule(nodes, new Rule("font", "class", "text12")) as HtmlElement;

			string topic, text, author;
			DateTime date;

			topic = topicNode.Text.Substring("נושא : ".Length-1);

			var dateString = ForumHandler.GetFromString(page, "text12>", "<");
			dateString[0] = HtmlStripper.StripFromHtml(dateString[0]);

			
			text = string.Empty;
			BuildString(nodes, ref text);
			
			author = string.Empty;
			date = DateTime.ParseExact(dateString[0], " dd/MM/yy  HH:mm", CultureInfo.InvariantCulture);

			ForumMessage m = new ForumMessage(topic, text, author, date);
			long.TryParse(msgId, out m.UniqueId);
			list.Add(m);
		}

		private void BuildString(HtmlNodeCollection nodes, ref string str)
		{
			if (nodes == null) return;
			foreach (HtmlNode node in nodes)
			{
				if (!(node is HtmlElement)) continue;
				var e = node as HtmlElement;
				if (e.Name == "script") continue;
				str += e.Text;
				BuildString(e.Nodes, ref str);
			}
		}

		private void GetAllMessageIds(string page, ref List<string> messageIds)
		{
			// DMsg(26228253 ,0
			string dmsg = "DMsg(";
			string ending = ",";

			messageIds = ForumHandler.GetFromString(page, dmsg, ending);
			messageIds.RemoveAt(0);
			int start=0, end=0;
			string tmp;

			while (true)
			{
				start = page.IndexOf(dmsg, end);
				if (start < 0) break;
				end = page.IndexOf(ending, start);
				tmp = page.Substring(start + dmsg.Length, end - start - dmsg.Length);
				if (tmp.Length < 4) continue;
				messageIds.Add(tmp.Replace(" ", string.Empty));
			}
			
		}

		private string GetAllVars(string page)
		{
//			ALLVAR = '875-18051-' + id + '-876' + '-' + MessageIsActive;
			string 
				av = "ALLVAR = '", 
				msgActive="' + '-' + MessageIsActive;";

			int start, end;
			string tmp;
			start = page.IndexOf(av);
			end = page.IndexOf(msgActive, start);
			tmp = page.Substring(start + av.Length, end - start - av.Length);
			// tmp == 875-18051-' + id + '-876
			tmp = tmp.Replace("' + id + '", "{0}");
			return tmp + "-1";
		}

		


		public Forum ExtractForum(long forumId)
		{
			throw new NotImplementedException();
		}

		public Forum ExtractForum(string url)
		{
			throw new NotImplementedException();
		}

		#endregion
	}
	public class YnetForumId
	{
		public long Major, Minor;
		public YnetForumId(long major, long minor) { Major = major; Minor = minor; }
		public override string ToString()
		{
			return string.Format("{0}-{1}", Major, Minor);
		}*/
	}
}
